<template>
  <div class="device-usage-statistics">
    <a-card :bordered="false" class="statistics-card">
      <template #title>
        <div class="card-title">
          <icon-bar-chart style="font-size: 20px; margin-right: 8px;" />
          <span>物资使用情况统计</span>
        </div>
      </template>

      <!-- 查询条件 -->
      <div class="query-section">
        <a-space wrap>
          <a-range-picker
            v-model="dateRange"
            :default-value="defaultDateRange"
            format="YYYY-MM-DD"
            style="width: 300px"
            @change="handleDateChange"
          />
          <a-button type="primary" @click="handleSearch">
            <template #icon><icon-search /></template>
            查询
          </a-button>
          <a-button @click="handleReset">
            <template #icon><icon-refresh /></template>
            重置
          </a-button>
        </a-space>
      </div>

      <!-- Tab切换 -->
      <a-tabs v-model:active-key="activeTab" @change="handleTabChange">
        <!-- 传感器统计 -->
        <a-tab-pane key="sensor" title="传感器统计">
          <div class="sensor-statistics">
            <!-- 传感器筛选条件 -->
            <div class="filter-section">
              <a-space wrap>
                <a-input
                  v-model="sensorQuery.modelId"
                  placeholder="请输入型号"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-input
                  v-model="sensorQuery.manufacturer"
                  placeholder="请输入生产厂家"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-input
                  v-model="sensorQuery.measureRange"
                  placeholder="请输入量程"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-button type="primary" @click="loadSensorStatistics">
                  <template #icon><icon-search /></template>
                  查询
                </a-button>
              </a-space>
            </div>

            <!-- 传感器统计表格 -->
            <a-table
              :columns="sensorColumns"
              :data="sensorData"
              :loading="sensorLoading"
              :pagination="false"
              :bordered="true"
              :scroll="{ x: 1000 }"
            >
              <template #totalCount="{ record }">
                <a-statistic :value="record.totalCount" :value-style="{ fontSize: '16px' }" />
              </template>
              <template #stockCount="{ record }">
                <a-statistic :value="record.stockCount" :value-style="{ fontSize: '16px', color: '#52c41a' }" />
              </template>
              <template #usedCount="{ record }">
                <a-statistic :value="record.usedCount" :value-style="{ fontSize: '16px', color: '#1890ff' }" />
              </template>
            </a-table>
          </div>
        </a-tab-pane>

        <!-- 耗材统计 -->
        <a-tab-pane key="consumable" title="耗材统计">
          <div class="consumable-statistics">
            <!-- 耗材筛选条件 -->
            <div class="filter-section">
              <a-space wrap>
                <a-input
                  v-model="consumableQuery.deviceName"
                  placeholder="请输入设备名称"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-input
                  v-model="consumableQuery.modelId"
                  placeholder="请输入型号"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-input
                  v-model="consumableQuery.manufacturer"
                  placeholder="请输入生产厂家"
                  allow-clear
                  style="width: 200px"
                >
                  <template #prefix><icon-search /></template>
                </a-input>
                <a-button type="primary" @click="loadConsumableStatistics">
                  <template #icon><icon-search /></template>
                  查询
                </a-button>
              </a-space>
            </div>

            <!-- 耗材统计表格 -->
            <a-table
              :columns="consumableColumns"
              :data="consumableData"
              :loading="consumableLoading"
              :pagination="false"
              :bordered="true"
              :scroll="{ x: 1200 }"
            >
              <template #remainingStock="{ record }">
                <a-statistic :value="record.remainingStock" :value-style="{ fontSize: '16px', color: '#52c41a' }" />
              </template>
              <template #usedCount="{ record }">
                <a-statistic :value="record.usedCount" :value-style="{ fontSize: '16px', color: '#1890ff' }" />
              </template>
              <template #projectUsage="{ record }">
                <a-button type="text" size="small" @click="showProjectUsage(record)">
                  查看详情
                </a-button>
              </template>
            </a-table>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 项目使用明细弹窗 -->
    <a-modal
      v-model:visible="projectUsageVisible"
      title="各项目使用数量明细"
      :width="800"
      :footer="false"
    >
      <a-table
        :columns="projectUsageColumns"
        :data="projectUsageData"
        :pagination="false"
        :bordered="true"
      >
        <template #usageCount="{ record }">
          <a-statistic :value="record.usageCount" :value-style="{ fontSize: '16px', color: '#1890ff' }" />
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import dayjs, { type Dayjs } from 'dayjs'
import {
  getSensorStatistics,
  getConsumableStatistics,
  type SensorStatisticsQuery,
  type ConsumableStatisticsQuery,
  type SensorStatisticsResp,
  type ConsumableStatisticsResp,
  type ProjectUsageDetail
} from '@/apis/generator/deviceStore'
// 图标使用小写形式，Arco Design会自动注册

// 默认日期范围（当前自然年）
const currentYear = dayjs().year()
const defaultDateRange = [dayjs(`${currentYear}-01-01`), dayjs(`${currentYear}-12-31`)]

// 日期范围
const dateRange = ref<[Dayjs, Dayjs]>(defaultDateRange as [Dayjs, Dayjs])

// 当前激活的Tab
const activeTab = ref('sensor')

// 传感器查询条件
const sensorQuery = ref<SensorStatisticsQuery>({
  modelId: '',
  manufacturer: '',
  measureRange: ''
})

// 耗材查询条件
const consumableQuery = ref<ConsumableStatisticsQuery>({
  deviceName: '',
  modelId: '',
  manufacturer: ''
})

// 传感器数据
const sensorData = ref<SensorStatisticsResp[]>([])
const sensorLoading = ref(false)

// 耗材数据
const consumableData = ref<ConsumableStatisticsResp[]>([])
const consumableLoading = ref(false)

// 项目使用明细
const projectUsageVisible = ref(false)
const projectUsageData = ref<ProjectUsageDetail[]>([])

// 传感器表格列
const sensorColumns = [
  {
    title: '设备名称',
    dataIndex: 'deviceName',
    width: 150,
    fixed: 'left'
  },
  {
    title: '型号',
    dataIndex: 'modelId',
    width: 120
  },
  {
    title: '生产厂家',
    dataIndex: 'manufacturer',
    width: 150
  },
  {
    title: '量程',
    dataIndex: 'measureRange',
    width: 120
  },
  {
    title: '总数量',
    dataIndex: 'totalCount',
    width: 120,
    slotName: 'totalCount'
  },
  {
    title: '库存数量',
    dataIndex: 'stockCount',
    width: 120,
    slotName: 'stockCount'
  },
  {
    title: '使用数量',
    dataIndex: 'usedCount',
    width: 120,
    slotName: 'usedCount'
  }
]

// 耗材表格列
const consumableColumns = [
  {
    title: '设备名称',
    dataIndex: 'deviceName',
    width: 150,
    fixed: 'left'
  },
  {
    title: '型号',
    dataIndex: 'modelId',
    width: 120
  },
  {
    title: '生产厂家',
    dataIndex: 'manufacturer',
    width: 150
  },
  {
    title: '剩余库存数量',
    dataIndex: 'remainingStock',
    width: 140,
    slotName: 'remainingStock'
  },
  {
    title: '使用数量',
    dataIndex: 'usedCount',
    width: 120,
    slotName: 'usedCount'
  },
  {
    title: '各项目使用数量',
    dataIndex: 'projectUsage',
    width: 150,
    slotName: 'projectUsage'
  }
]

// 项目使用明细表格列
const projectUsageColumns = [
  {
    title: '项目名称',
    dataIndex: 'projectName',
    width: 200
  },
  {
    title: '使用数量',
    dataIndex: 'usageCount',
    width: 150,
    slotName: 'usageCount'
  }
]

// 日期变化处理
const handleDateChange = (dates: [Dayjs, Dayjs] | null) => {
  if (dates) {
    dateRange.value = dates
  }
}

// Tab切换处理
const handleTabChange = (key: string) => {
  if (key === 'sensor') {
    loadSensorStatistics()
  } else if (key === 'consumable') {
    loadConsumableStatistics()
  }
}

// 查询
const handleSearch = () => {
  if (activeTab.value === 'sensor') {
    loadSensorStatistics()
  } else {
    loadConsumableStatistics()
  }
}

// 重置
const handleReset = () => {
  dateRange.value = defaultDateRange as [Dayjs, Dayjs]
  sensorQuery.value = {
    modelId: '',
    manufacturer: '',
    measureRange: ''
  }
  consumableQuery.value = {
    deviceName: '',
    modelId: '',
    manufacturer: ''
  }
  handleSearch()
}

// 加载传感器统计
const loadSensorStatistics = async () => {
  try {
    sensorLoading.value = true
    const query: SensorStatisticsQuery = {
      startDate: dateRange.value[0].format('YYYY-MM-DD'),
      endDate: dateRange.value[1].format('YYYY-MM-DD'),
      ...sensorQuery.value
    }
    
    const res = await getSensorStatistics(query)
    if (res.success && res.data) {
      sensorData.value = res.data
    } else {
      Message.error(res.message || '查询传感器统计失败')
      sensorData.value = []
    }
  } catch (error: any) {
    console.error('查询传感器统计失败:', error)
    Message.error(error?.message || '查询传感器统计失败')
    sensorData.value = []
  } finally {
    sensorLoading.value = false
  }
}

// 加载耗材统计
const loadConsumableStatistics = async () => {
  try {
    consumableLoading.value = true
    const query: ConsumableStatisticsQuery = {
      startDate: dateRange.value[0].format('YYYY-MM-DD'),
      endDate: dateRange.value[1].format('YYYY-MM-DD'),
      ...consumableQuery.value
    }
    
    const res = await getConsumableStatistics(query)
    if (res.success && res.data) {
      consumableData.value = res.data
    } else {
      Message.error(res.message || '查询耗材统计失败')
      consumableData.value = []
    }
  } catch (error: any) {
    console.error('查询耗材统计失败:', error)
    Message.error(error?.message || '查询耗材统计失败')
    consumableData.value = []
  } finally {
    consumableLoading.value = false
  }
}

// 显示项目使用明细
const showProjectUsage = (record: ConsumableStatisticsResp) => {
  if (record.projectUsageDetails && record.projectUsageDetails.length > 0) {
    projectUsageData.value = record.projectUsageDetails
    projectUsageVisible.value = true
  } else {
    Message.info('暂无项目使用明细')
  }
}

// 初始化加载
onMounted(() => {
  loadSensorStatistics()
})
</script>

<style scoped lang="scss">
.device-usage-statistics {
  padding: 20px;

  .statistics-card {
    .card-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 18px;
      font-weight: 500;
    }
  }

  .query-section {
    margin-bottom: 20px;
    padding: 16px;
    background: #fafafa;
    border-radius: 4px;
  }

  .filter-section {
    margin-bottom: 16px;
    padding: 12px;
    background: #fafafa;
    border-radius: 4px;
  }

  .sensor-statistics,
  .consumable-statistics {
    margin-top: 16px;
  }
}
</style>

